package com.amorcloud.pig.activity;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.amorcloud.pig.R;
import com.amorcloud.pig.adapter.CheckDataAdapter;
import com.amorcloud.pig.bean.CheckBean;
import com.amorcloud.pig.bean.GetDeviceNoResultBean;
import com.amorcloud.pig.bean.GetGroupNoResultBean;
import com.amorcloud.pig.bean.StopCheckResultBean;
import com.amorcloud.pig.utils.CheckDaoUtil;
import com.amorcloud.pig.utils.DateUtil;
import com.amorcloud.pig.utils.HttpUtils;
import com.amorcloud.pig.utils.NetworkUtil;
import com.amorcloud.pig.utils.SharedPreferencesUtils;
import com.amorcloud.pig.utils.ToastUtil;
import com.amorcloud.pig.widget.UploadSuccessDialog;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class CheckActivity extends BaseActivity implements View.OnClickListener {

    private Button btnStart, btnStop;
    private ImageView groupNoRefresh, deviceNoRefresh;
    private Spinner mSPGroupNo, mSPDeviceNo;
    private ListView listView;
    private TextView tvActualCount, tvTargetCount;
    //按钮倒计时timer
    private Timer timer;
    private int time = 5;
    //母猪场名称
    private String farmName;
    private Gson mGson = new Gson();
    //sp 数据源
    private List<String> groupNoList = new ArrayList<>();
    // 批次信息列表
    private List<GetGroupNoResultBean.DataListBean> groupNoBeans;
    // 设备信息列表
    private List<String> deviceNoList = new ArrayList<>();
    //刷新按钮动画
    private Animation rotationAnimation;
    private RadioGroup radioGroup;
    // 盘点类型
    private int checkType = 0;
    //当前批次号的盘点数量
    private String groupCount = "";
    private CheckDataAdapter checkDataAdapter;
    private List<String> checkDataList = new ArrayList<>();
    private int actualCount;

    @Override
    protected void init() {
        setContentView(R.layout.activity_check);
        initCustomToolbar(this);
        initView();
        initData();
    }

    private void initView() {
        btnStart = findViewById(R.id.btn_start_check);
        btnStart.setOnClickListener(this);
        btnStop = findViewById(R.id.btn_stop_check);
        btnStop.setOnClickListener(this);
        btnStop.setEnabled(false);
        tvActualCount = findViewById(R.id.tv_actual_count);
        tvTargetCount = findViewById(R.id.tv_target_count);
        listView = findViewById(R.id.lv_check_data);
        listView.addHeaderView(LayoutInflater.from(this).inflate(R.layout.header_2_column, listView, false));
        groupNoRefresh = findViewById(R.id.img_check_group_no_refresh);
        groupNoRefresh.setOnClickListener(this);
        deviceNoRefresh = findViewById(R.id.img_check_device_refresh);
        deviceNoRefresh.setOnClickListener(this);
        mSPGroupNo = findViewById(R.id.sp_check_group_no);
        mSPGroupNo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (groupNoBeans != null) {
                    groupCount = groupNoBeans.get(position).getCurNo();
                    Log.d("leihuiming", "groupCount = " + groupCount);
                    tvTargetCount.setText("任务盘点数量：" + groupCount);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        mSPDeviceNo = findViewById(R.id.sp_check_device_no);
        mSPDeviceNo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectValue = mSPDeviceNo.getSelectedItem().toString();
                if (!selectValue.startsWith("请")) {
                    new Thread(){
                        @Override
                        public void run() {
                            super.run();
                            try {
                                String result = HttpUtils.checkDeviceStatus(mSPDeviceNo.getSelectedItem().toString());
                                Log.d("leihuiming", "device status result = " + result);
                                JSONObject object = new JSONObject(result);
                                if(object.has("MsgCode")){
                                    if("1".equals(object.get("MsgCode"))) {
                                        ToastUtil.showToastOnThread(CheckActivity.this, "该设备正在使用。");
                                        mHandler.sendEmptyMessage(1); //该设备正在使用, 只能停止盘点
                                        return;
                                    } else if("0".equals(object.get("MsgCode"))){
                                        mHandler.sendEmptyMessage(4); //设备未使用，可正常盘点，恢复按钮状态。
                                        return;
                                    }
                                } else {
                                    ToastUtil.showToastOnThread(CheckActivity.this, "设备状态接口异常");
                                    mHandler.sendEmptyMessage(4); //开始盘点报错，恢复按钮状态。
                                    return;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        rotationAnimation = AnimationUtils.loadAnimation(this, R.anim.anim_rotate_refresh);

        radioGroup = findViewById(R.id.check_radio_group);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int radioId = group.getCheckedRadioButtonId();
                switch (radioId) {
                    case R.id.rb_chuku:
                        checkType = 0;
                        break;
                    case R.id.rb_ruku:
                        checkType = 1;
                        break;
                    case R.id.rb_richang:
                        checkType = 2;
                        break;
                    case R.id.rb_siwang:
                        checkType = 3;
                        break;
                    default:
                        break;
                }
            }
        });
    }

    private void initData() {
        farmName = (String) SharedPreferencesUtils.getParam("farmName", "");
        deviceNoList.add("请选择设备...");
        displayGroupNo();
        displayDeviceNo();
        checkDataAdapter = new CheckDataAdapter(this, checkDataList);
        listView.setAdapter(checkDataAdapter);
    }

    private void displayDeviceNo() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                String result = HttpUtils.getDeviceNo();
                Log.d("leihuiming", "get DeviceNo result = " + result);
                GetDeviceNoResultBean bean = mGson.fromJson(result, GetDeviceNoResultBean.class);
                if (bean != null) {
                    if ("0".equals(bean.getMsgCode())) {
                        if (bean.getRFIDList().size() > 0) {
                            deviceNoList.addAll(bean.getRFIDList());
                            mHandler.sendEmptyMessage(3);
                        }
                    } else {
                        //Toast.makeText(CheckActivity.this, "MsgCode: " + bean.getMsgCode() + " Msg: " + bean.getMsg(), Toast.LENGTH_SHORT).show();
                        ToastUtil.showToastOnThread(CheckActivity.this, "MsgCode: " + bean.getMsgCode() + " Msg: " + bean.getMsg());
                    }
                }
            }
        }.start();
    }

    private void displayGroupNo() {
        if (TextUtils.isEmpty(farmName)) {
            Toast.makeText(this, "未设置农场名", Toast.LENGTH_SHORT).show();
        } else {
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    String result = HttpUtils.getGroupNo(farmName);
                    Log.d("leihuiming", "get GroupNo result = " + result);
                    GetGroupNoResultBean bean = mGson.fromJson(result, GetGroupNoResultBean.class);
                    if (bean != null) {
                        if ("0".equals(bean.getMsgCode())) {
                            if (bean.getDataList().size() > 0) {
                                groupNoBeans = bean.getDataList();
                                for (int i = 0; i < bean.getDataList().size(); i++) {
                                    groupNoList.add(bean.getDataList().get(i).getGroupNo());
                                }
                                mHandler.sendEmptyMessage(2);
                            }
                        } else {
                            //Toast.makeText(CheckActivity.this, "MsgCode: " + bean.getMsgCode() + " Msg: " + bean.getMsg(), Toast.LENGTH_SHORT).show();
                            ToastUtil.showToastOnThread(CheckActivity.this, "MsgCode: " + bean.getMsgCode() + " Msg: " + bean.getMsg());
                        }
                    }
                }
            }.start();
        }
    }

    private void doCheck(final CheckBean checkBean, final int startOrStop) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    /*if(startOrStop == 1) {
                        String result = HttpUtils.checkDeviceStatus(mSPDeviceNo.getSelectedItem().toString());
                        Log.d("leihuiming", "device status result = " + result);
                        JSONObject object = new JSONObject(result);
                        if(object.has("MsgCode")){
                            if(!"0".equals(object.get("MsgCode"))) {
                                ToastUtil.showToastOnThread(CheckActivity.this, "设备状态异常, 错误码：" + object.get("MsgCode"));
                                mHandler.sendEmptyMessage(4); //开始盘点报错，恢复按钮状态。
                                return;
                            }
                        } else {
                            ToastUtil.showToastOnThread(CheckActivity.this, "设备状态异常");
                            mHandler.sendEmptyMessage(4); //开始盘点报错，恢复按钮状态。
                            return;
                        }
                    }*/
                    String result = HttpUtils.pigCheck(checkBean, startOrStop);
                    Log.d("leihuiming", "do check = result = " + result);
                    if (startOrStop == 1) { //开始盘点
                        startCheck(result);
                    } else { //停止盘点
                        stopChceck(result);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void startCheck(String json) {
        try {
            JSONObject object = new JSONObject(json);
            if (object.has("MsgCode") && "0".equals(object.get("MsgCode"))) {
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        time--;
                        mHandler.sendEmptyMessage((time == 0 ? 1 : 0));
                    }
                }, 1000, 1000);
            } else {
                mHandler.sendEmptyMessage(4);
                ToastUtil.showToastOnThread(CheckActivity.this, "MsgCode: " + object.get("MsgCode") + " Msg: " + object.get("Msg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void stopChceck(String json) {
        StopCheckResultBean bean = mGson.fromJson(json, StopCheckResultBean.class);
        if ("0".equals(bean.getMsgCode())) {
            if (bean.getCount() > 0) {
                checkDataList.clear();
                checkDataList = bean.getData();
                checkBean.setCheckID(bean.getID());
                Message message = Message.obtain();
                actualCount = bean.getCount();
                if (groupCount.equals(String.valueOf(bean.getCount()))) {
                    //显示盘点成功dialog
                    message.what = 5;
                    message.obj = bean.getCount();
                    mHandler.sendMessage(message);
                    checkBean.setCheckErMsg(bean.getMsg());
                    CheckDaoUtil.insert(checkBean);
                    checkBean = null;
                } else {
                    message.what = 6;//显示盘点失败dialog
                    message.arg1 = bean.getCount() - Integer.parseInt(groupCount);
                    mHandler.sendMessage(message);
                }
            } else {
                ToastUtil.showToastOnThread(CheckActivity.this, "盘点数量为0, 请重新盘点！");
            }
        } else {
            ToastUtil.showToastOnThread(CheckActivity.this, "盘点失败, 请重新盘点！错误码：" + bean.getMsgCode());
        }
    }

    CheckBean checkBean;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start_check:
                if(NetworkUtil.isNetworkConnected(this)) {
                    if (mSPDeviceNo.getSelectedItem() == null ||
                            mSPGroupNo.getSelectedItem() == null ||
                            mSPDeviceNo.getSelectedItem().toString().startsWith("请")) {
                        Toast.makeText(this, "请选择要盘点的数据", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    btnStop.setEnabled(false);
                    btnStart.setEnabled(false);
                    checkDataList.clear();
                    checkDataAdapter.setData(checkDataList);
                    timer = new Timer(true);
                    //创建盘点对象
                    createCheckBean();
                    doCheck(checkBean, 1); //开始盘点
                } else {
                    Toast.makeText(this, "网络错误，请设置网络。", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_stop_check:
                if(NetworkUtil.isNetworkConnected(this)) {
                    if (mSPDeviceNo.getSelectedItem() == null ||
                            mSPGroupNo.getSelectedItem() == null ||
                            mSPDeviceNo.getSelectedItem().toString().startsWith("请")) {
                        Toast.makeText(this, "请选择要盘点的数据", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    btnStart.setEnabled(true);
                    btnStop.setEnabled(false);
                    if (checkBean == null) {
                        createCheckBean();
                    }
                    doCheck(checkBean, 0);
                } else {
                    Toast.makeText(this, "网络错误，请设置网络。", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.img_check_group_no_refresh:
                groupNoRefresh.startAnimation(rotationAnimation);
                groupNoList.clear();
                displayGroupNo();
                break;
            case R.id.img_check_device_refresh:
                deviceNoRefresh.startAnimation(rotationAnimation);
                deviceNoList.clear();
                deviceNoList.add("请选择设备...");
                displayDeviceNo();
                break;
            default:
                break;
        }
    }

    private void createCheckBean() {
        checkBean = new CheckBean();
        checkBean.setRfidNumber(mSPDeviceNo.getSelectedItem().toString());
        checkBean.setCheckType(checkType);
        checkBean.setOddNumber(mSPGroupNo.getSelectedItem().toString());
        checkBean.setDateTime(DateUtil.getYMDHMSStrDate(System.currentTimeMillis()));
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0: //停止盘点不可点击并显示倒计时
                    btnStop.setText("停止盘点(" + time + ")");
                    break;
                case 1://倒计时结束，按钮恢复可以点击状态
                    btnStop.setText("停止盘点");
                    btnStop.setEnabled(true);
                    btnStart.setEnabled(false);
                    if(timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    time = 5;
                    break;
                case 2://初始化 获取groupNo
                    if (groupNoList.size() > 0) {
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(CheckActivity.this, android.R.layout.simple_spinner_item, groupNoList);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        mSPGroupNo.setAdapter(adapter);
                    } else {
                        mSPGroupNo.setAdapter(null);
                    }
                    break;
                case 3:// 初始化设备号
                    //deviceNoRefresh.clearAnimation();
                    if (deviceNoList.size() > 0) {
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(CheckActivity.this, android.R.layout.simple_spinner_item, deviceNoList);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        mSPDeviceNo.setAdapter(adapter);
                    } else {
                        mSPDeviceNo.setAdapter(null);
                    }
                    break;
                case 4: //开始盘点报错
                    btnStart.setEnabled(true);
                    btnStop.setEnabled(false);
                    break;
                case 5://停止盘点，盘点成功，显示成功dialog
                    int count = (int) msg.obj;
                    Dialog dialog = UploadSuccessDialog.CreateCheckSuccessDialog(CheckActivity.this, count);
                    dialog.show();
                    final WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
                    params.width = 650;
                    params.height = 550;
                    dialog.getWindow().setAttributes(params);
                    checkDataAdapter.setData(checkDataList);
                    tvActualCount.setText("实际盘点数量：" + actualCount);
                    break;
                case 6: //停止盘点，盘点失败，显示失败dialog
                    Dialog failDialog = CreateCheckFailDialog(msg.arg1);
                    failDialog.show();
                    final WindowManager.LayoutParams params1 = failDialog.getWindow().getAttributes();
                    params1.width = 800;
                    params1.height = 750;
                    failDialog.getWindow().setAttributes(params1);
                    checkDataAdapter.setData(checkDataList);
                    tvActualCount.setText("实际盘点数量：" + actualCount);
                    break;
                default:
                    break;
            }
        }
    };

    public Dialog CreateCheckFailDialog(int successCount) {
        final Dialog dialog = new Dialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_check_fail, null);
        final EditText errorMsg = view.findViewById(R.id.etv_check_fail_common);
        TextView message = view.findViewById(R.id.check_fail_count);
        final Button sureButton = view.findViewById(R.id.btn_sure);
        sureButton.setEnabled(false);
        errorMsg.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                Log.d("leihuiming", "beforeTextChanged s= " + s + " count=" + count);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.d("leihuiming", "onTextChanged s= " + s + " count=" + count);
                if (s.toString().length() >= 4) {
                    sureButton.setEnabled(true);
                } else {
                    sureButton.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.d("leihuiming", "afterTextChanged s= " + s.toString());
            }
        });

        sureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkBean.setCheckErMsg(errorMsg.getText().toString());
                CheckDaoUtil.insert(checkBean);
                checkBean = null;
                dialog.dismiss();
            }
        });
        if (successCount < 0) {
            message.setText(Html.fromHtml("猪只数量缺失<font color='#FF0000'>" + Math.abs(successCount) + "</font>只"));
        } else {
            message.setText(Html.fromHtml("猪只数量增多<font color='#FF0000'>" + successCount + "</font>只"));
        }
        dialog.setContentView(view);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        return dialog;
    }


}
